package com.wsd.bookkeeping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsd.bookkeeping.entity.Account;
import com.wsd.bookkeeping.entity.Comment;
import com.wsd.bookkeeping.entity.query.CommentQuery;
import com.wsd.bookkeeping.mapper.CommentMapper;
import com.wsd.bookkeeping.service.AccountService;
import com.wsd.bookkeeping.service.CommentService;
import com.wsd.exception.RRException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Value("${query.page-size}")
    private Integer pageSize;

    @Resource
    private AccountService accountService;

    @Override
    public List<Map<String, Object>> queryByPage(CommentQuery commentQuery) {
        commentQuery.setPageSize(pageSize);
        commentQuery.setStartNumber((commentQuery.getCurPage() - 1) * pageSize);
        return baseMapper.queryByPage(commentQuery);
    }

    @Override
    public Map<String, Object> queryBookInfo(Integer bookId) throws RRException, InterruptedException {
        Map<String, Object> accountInfoMap = new HashMap<>();

        // 创建一个线程数量为3的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        executorService.submit(() -> {
            // 用户列表
            List<Map<String, Object>> userList = accountService.queryUserListByBookId(bookId);
            accountInfoMap.put("userList", userList);
        });

       executorService.submit(() -> {
           // 评论数量
           QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq("book_id", bookId);
           Long commentCount = baseMapper.selectCount(queryWrapper);
           accountInfoMap.put("commentCount", commentCount);
       });

       executorService.submit(() -> {
           // 创建日期
           Account account = accountService.getById(bookId);
           accountInfoMap.put("account", account);
       });

       // 停止接收新任务, 当提交的任务全部执行完毕后, 线程池关闭
       executorService.shutdown();
       executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);

        return accountInfoMap;
    }
}
